<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="is--card">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="备库需求单号" value="demand_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.sku.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
            <el-option label="asin" value="asin"></el-option>
          </el-select>
          <VBatchInput v-model="form.sku.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VSelect v-model="form.demand_form" :options="options.demand_form" multiple collapse-tags style="min-width: 160px" placeholder="备库需求单类型" />
        <VSelect v-model="form.demand_type" :options="options.demand_type" multiple collapse-tags style="min-width: 160px" placeholder="备库需求类型" />
        <VSelect v-model="form.product_level" :options="options.product_level" multiple collapse-tags style="min-width: 160px" placeholder="备库单等级" />
        <VCascader v-model="form.create_user_id" placeholder="申请人员" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.department_name" placeholder="需求部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VCascader v-model="form.develop_department_name" placeholder="开发部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.demand_status" :options="options.demand_status" multiple collapse-tags style="min-width: 160px" placeholder="审核状态" />
        <VSelect v-model="form.country" :options="options.country" multiple collapse-tags style="min-width: 160px" placeholder="国家" />
        <VGroup>
          <el-select v-model="form.warehouse.type" class="w-28" @change="form.warehouse.value = []">
            <el-option label="目的仓平台" value="destination_warehouse"></el-option>
            <el-option label="目的仓" value="plan_destination_warehouse"></el-option>
          </el-select>
          <VSelect v-if="form.warehouse.type === 'destination_warehouse'" v-model="form.warehouse.value" placeholder="请选择" :options="options.destination_warehouse" multiple
            collapse-tags style="min-width: 160px" />
          <VSelect v-else v-model="form.warehouse.value" placeholder="请选择" :options="options.plan_destination_warehouse" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.purchase_status" :options="options.purchase_status" multiple collapse-tags style="min-width: 140px" placeholder="采购状态" />
        <VSelect v-model="form.sku_purchase_status" :options="options.sku_purchase_status" multiple collapse-tags style="min-width: 140px" placeholder="sku采购状态" />
        <VSelect v-model="form.is_deliver_abnormal" :options="options.is_deliver_abnormal" multiple collapse-tags style="min-width: 140px" placeholder="是否到货异常" />
        <VCascader v-model="form.sale_id" multiple collapse-tags style="min-width: 160px" placeholder="负责销售" />
        <VMoreCascader v-model="form.supplier_address" :propsValue="{ checkStrictly: true }" placeholder="供应商地址" style="min-width: 160px"></VMoreCascader>
        <VSelect v-model="form.platform" :options="options.platform" multiple collapse-tags filterable clearable style="min-width: 160px" placeholder="平台" />
        <VSelect v-model="form.feishu_audit_status" :options="options.feishu_audit_status" multiple collapse-tags filterable clearable style="min-width: 160px" placeholder="飞书审核状态" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 130px">
            <el-option label="申请日期" value="create_time"></el-option>
            <el-option label="审核日期" value="audit_time"></el-option>
            <el-option label="需求日期" value="demand_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
        <teleport v-if="demandTabsLoad" to="#demand-tabs">
          <el-tabs v-model="form.type" @tab-change="tabChange">
            <el-tab-pane v-for="(d, i) in options.type" :key="i" :label="`${d.label}(${d.num || 0})`" :name="d.value"></el-tab-pane>
          </el-tabs>
        </teleport>
      </template>
      <template #toolbar_btns>
        <div id="demand-tabs" class="w-full" v-dom-load="() => demandTabsLoad = true"></div>
        <VButton auth="/purchase/demand/demand/add" type="primary" @click="create(tableRef)"><i class="dk-iconfont icon-Plus" />添加</VButton>
        <VAudit :auth="(options.batch_audit_status || []).map(d => d.auth)" field="pd_id" url="/v1/purchase-demand/purchase-demand/batch-audit" :tableRef="tableRef"
          :list="options.batch_audit_status" statusField="demand_status" @success="query" />
        <VButton auth="/purchase/demand/demand/manual_completion_order" :loading="loadings.complete" @click="handleBatch('complete')">手动完结备库需求</VButton>
        <VButton auth="/purchase/demand/demand/submit" :loading="loadings.submit" @click="handleBatch('submit')">批量提交
        </VButton>
        <VImport auth="/purchase/demand/demand/batchimport" :tableRef="tableRef" importUrl="/v1/purchase-demand/purchase-demand/import"
          downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/%E5%A4%87%E8%B4%A7%E8%AE%A1%E5%88%92%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx" class="ml-auto"
          @success="query" />
        <VExport auth="/purchase/demand/demand/export" mainKey="pd_id" :name="baseName" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import VMoreCascader from '@/components/VMoreCascader/index.vue'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { resMessage } from "@/utils/res"
const router = useRouter()

const baseName = 'purchase_demand'
const tableRef = ref()
const logRef = ref()
const demandTabsLoad = ref(false)
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase_demand_change' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
  getTotal()
})

// 获取状态数量
const getTotal = async (params = { type: 0 }) => {
  if (!options.value.type) return
  await api.total(params).then(res => {
    options.value.type.forEach(t => {
      t.num = res.data.find(d => d.value === t.value)?.num || 0
    })
  })
}

const tabValue = ref(0)
const tabChange = name => {
  tabValue.value = name
  query()
}

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pd_ids = selection.map(d => d.pd_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    complete: () => {
      showLoading()
      ElMessageBox.confirm('是否确认完结选择的备库需求？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.complete({ pd_ids }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          closeLoading()
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ pd_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(() => {
        closeLoading()
      })
    },
  }
  handle[name]()
}
// 单行操作
const handleRow = (name, row, rowIndex) => {
  const { pd_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      addRef?.value.open(pd_id, true)
    },
    edit: () => {
      addRef?.value.open(pd_id)
    },
    remove: () => {
      showLoading()
      api.remove({ pd_id }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(() => {
        closeLoading()
      })
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ pd_ids: [pd_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(() => {
        closeLoading()
      })
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          api[name]({ pd_id }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    back: () => {
      ElMessageBox.confirm('是否确认反审到待提交状态？', '反审', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          api[name]({ pd_id }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    toPath: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { input: { type: 'demand_no', value: row.demand_no } } }))
      router.push('/demand/change')
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, pd_id })
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 92 },
  formConfig: {
    data: {
      type: 0,
      sku: { type: 'sku', value: '' }, // 组合
      input: { type: 'demand_no', value: '' }, // 组合
      warehouse: { type: 'destination_warehouse', value: [] }, // 组合
      dateRange: { type: 'create_time', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    {
      title: '备库需求单号', minWidth: 160, slots: {
        default: ({ row }) => {
          return <div class='nm flex flex-col'>
            {row.change_status_name ? <VText type='button' value='变更' class='ml-12' onClick={() => handleRow('toPath', row)}></VText> : ''}
            <VText type='button' value={row.demand_no} copy onClick={() => handleRow('look', row)}></VText>
          </div>
        }
      }
    },
    {
      title: '生成类别', field: 'process_type_name', minWidth: 100, slots: {
        default: ({ row }) => <VText value={row.process_type_name} />
      }
    },
    {
      title: '备库需求单类型', field: 'demand_form_name', minWidth: 220, slots: {
        default: ({ row }) => <div>
          <VText value={row.demand_form_name} />
          <VText title='等级' value={row.product_level_name} />
          <VText title='关联单据号' value={row.relation_no} title-position='top' />
        </div>
      }
    },
    {
      title: '备库需求类型', field: 'demand_type_name', minWidth: 140, slots: {
        default: ({ row }) => <VText value={row.demand_type_name} />
      }
    },
    {
      title: '开发部门', field: 'develop_department_name', minWidth: 180, slots: {
        default: ({ row }) => <VText value={row.develop_department_name} line={2} />
      }
    },
    {
      title: '需求部门', field: 'department_name', minWidth: 180, slots: {
        default: ({ row }) => <VText value={row.department_name} line={2} />
      }
    },
    {
      title: '部门备货金额信息', field: '', minWidth: 250, slots: {
        default: ({ row }) => <div>
          <VText title='事业处已备货金额' value={row.first_department_amount || ''} />
          <VText title='部门' value={row.department_amount_w || ''} />
          <VText title='已使用' value={row.use_amount_w || ''} />
          <VText title='剩余' value={row.leave_amount_w || ''} />
        </div>
      }
    },
    {
      title: '备货总数量/总金额', field: '', minWidth: 170, slots: {
        default: ({ row }) => <div>
          <VText title='总数量' value={row.demand_num || ''} />
          <VText title='总金额CNY' value={row.demand_amount_w || ''} />
        </div>
      }
    },
    {
      title: '申请人/申请日期', field: '', minWidth: 180, slots: {
        default: ({ row }) => <div>
          <VText value={row.create_user} />
          <VText value={row.create_time} />
        </div>
      }
    },
    {
      title: '审核状态/审核日期', field: '', minWidth: 180, slots: {
        default: ({ row }) => <div>
          <VText value={row.demand_status_name} />
          <VText value={row.audit_time} />
        </div>
      }
    },
    {
      title: '飞书审核状态', field: '', minWidth: 180, slots: {
        default: ({ row }) => <div>
          <VText title='状态' value={row.feishu_audit_status_name} />
          <VText title='节点' value={row.feishu_next_audit_name} />
        </div>
      }
    },
    {
      title: '驳回原因', field: 'audit_remark', minWidth: 180, slots: {
        default: ({ row }) => <VText value={row.audit_remark} />
      }
    },
    {
      title: '采购状态', field: 'purchase_status_name', minWidth: 140, slots: {
        default: ({ row }) => <VText value={row.purchase_status_name} />
      }
    },
    {
      field: 'remark', title: '备注', minWidth: 150, showOverflow: true, slots: {
        default: ({ row }) => <VText value={row.remark} line={2} />
      }
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { pd_id, demand_status } = row
          // 需求单状态1待提交2待运营经理审核3待运营总监审核4待供应链总监审核5待采购总监审核6待采购经理审核7待计划经理审核8已驳回9审核通过10已作废11已完结
          return [<div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/demand/demand/view" link type="primary" onClick={() => handleRow('look', row)}>查看</VButton>
            {[1, 8].includes(demand_status) ? <VButton auth="/purchase/demand/demand/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton> : ''}
            {[1, 8].includes(demand_status) ? <VButton auth="/purchase/demand/demand/submit" link type="primary" loading={loadings['submit' + rowIndex]} onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            {[1, 8].includes(demand_status) ? <VButton auth="/purchase/demand/demand/void" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
            {[9].includes(demand_status) ? <VButton auth="/purchase/demand/demand/countertrial" link type="primary" onClick={() => handleRow('back', row)}>反审</VButton> : ''}
            {[2, 3, 4, 5, 6, 7].includes(demand_status) ? <VButton auth="/purchase/demand/demand/cancel" link type="primary" onClick={() => handleRow('remove', row)}>取消</VButton> : ''}
            {[8, 10, 11].includes(demand_status) ? <VButton auth="/purchase/demand/demand/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton> : ''}
          </div>]
        }
      }
    }
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        await getTotal({ ...form, ...page })
        return api.query({ ...form, ...page }).then(res => {
          options.value.type.forEach(d => {
            if (d.value === tabValue.value) {
              d.num = res.total
            }
          })
          return res
        })
      }
    }
  }
})
</script>
  